<?php
/**
 * Token.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/6/10
 * Time: 14:28
 */
namespace app\api\open\member;

use app\api\open\Base;
use app\common\utils\rsa\Rsa1024;
use think\Cache;

abstract class Token extends Base
{
    protected $member_id = null;
    protected $token_data = [];

    public function __construct($param=[])
    {
        parent::__construct($param);

        if(empty($this->params['access_token']))
        {
            throw new \Exception("access_token required");
        }
        $access_token = explode("|",Rsa1024::decryptByPri($this->params['access_token']));

        if(empty($access_token[1]))
        {
            throw new \Exception("access_token redis_key error");
        }

        $redis_key = $access_token[1];

        $cache = Cache::store('redis');
        $redisHandler = $cache->handler();

        $resultEncode = $redisHandler->get($redis_key);
        if(empty($resultEncode))
        {
            throw new \Exception("TOKEN_EXPIRED_PLEASE_LOGIN_AGAIN",302);
        }
        $this->token_data = json_decode($resultEncode,true);
        if($access_token[0] === 'single')
        {
            // 单点登录
            if($this->token_data['__uniqid__'] !== $access_token[2])
            {
                throw new \Exception("TOKEN_ERROR_PLEASE_LOGIN_AGAIN",302);
            }
        }
        $this->member_id = $this->token_data['id'];
        // 操作用户相关模块缓存60分钟
        @$redisHandler->setex($redis_key,60*60,$resultEncode);
    }
}